/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.core.token;

import com.arisgo.cloud.core.Constant;
import com.arisgo.cloud.core.redis.UserInfo;
import com.arisgo.cloud.core.token.config.TokenProperties;
import com.arisgo.cloud.core.utils.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.auth0.jwt.RegisteredClaims.AUDIENCE;
import static com.auth0.jwt.RegisteredClaims.ISSUER;
import static com.auth0.jwt.RegisteredClaims.SUBJECT;

/**
 * @author Arisgo
 * @since 2024/5/31
 */
@Component
@AllArgsConstructor
public class TokenGenerator {

    private final TokenProperties tokenProperties;
    protected ObjectMapper mapper = new ObjectMapper();
    protected final RedisTemplate<String, Object> redisTemplate;

    public Map<Object, Object> generator(UserInfo user) {
        Map<Object, Object> token = Maps.newHashMap();
        token.putAll(mapper.convertValue(user, Map.class));
        token.put(Constant.REFRESH_TOKEN, refreshToken(user.getUserId().toString()));
        token.put(Constant.ACCESS_TOKEN, accessToken(user));
        redisTemplate.expire(Constant.TOKEN_PREFIX + user.getUserId(), tokenProperties.getRefreshTokenExpireAt(), TimeUnit.HOURS);
        return token;
    }

    /**
     * 刷新access token
     *
     * @param user 用户信息
     * @return token
     */
    public String accessToken(UserInfo user) {
        Map<String, Object> claims = Maps.newHashMap();
        claims.put(ISSUER, "ArisgoCloud");
        claims.put(SUBJECT, "user");
        claims.put(AUDIENCE, user.getUserId().toString());
        claims.put(Constant.LOGIN_USER, mapper.convertValue(user, Map.class));
        String token = JwtUtil.sign(tokenProperties.getTokenSecret(), tokenProperties.getAccessTokenExpireAt(), claims);
        // 设置缓存
        redisTemplate.opsForHash().put(Constant.TOKEN_PREFIX + user.getUserId(), Constant.ACCESS_TOKEN, token);
        return token;
    }

    /**
     * 创建 refresh token
     *
     * @param userId 用户id
     * @return refresh token
     */
    public String refreshToken(@Nonnull String userId) {
        Map<String, Object> claims = Maps.newHashMap();
        claims.put(ISSUER, "ArisgoCloud");
        claims.put(SUBJECT, "user");
        claims.put(AUDIENCE, userId);
        claims.put("type", "refresh");
        String token = JwtUtil.sign(tokenProperties.getTokenSecret(), tokenProperties.getRefreshTokenExpireAt(), claims);
        // 设置缓存
        redisTemplate.opsForHash().put(Constant.TOKEN_PREFIX + userId, Constant.REFRESH_TOKEN, token);
        return token;
    }

    public long getAccessTokenExpireAt() {
        return tokenProperties.getAccessTokenExpireAt();
    }

    public long getRefreshTokenExpireAt() {
        return tokenProperties.getRefreshTokenExpireAt();
    }

    public String getTokenSecret() {
        return tokenProperties.getTokenSecret();
    }

}
